from http_requests import HttpRequest
import easyocr
import os
import random
import re
from ocr import imgOcr, imgPrivateOcr
from datetime import datetime
import json
ocr_engine = easyocr.Reader(['ch_sim', 'en'])
import time
import base64
import io
from PIL import Image

# keyword = "QM_April12"

def extract_keywords(text):
    # 合并后的正则表达式：
    # 1. 匹配手机号码（1开头，11位）|
    # 2. 匹配其他关键词（6-20位字母数字下划线减号）
    pattern = r'(?:1[3-9]\d{9}|[a-zA-Z0-9_-]{6,20})'

    keywords = re.findall(pattern, text)
    # 去重（保留顺序）
    return list(dict.fromkeys(keywords))


def privateMessage(http_client,path_or_base64,private_message_List):

    #总发送私信数量  日次数50次
    #随机触发
    # http_client = HttpRequest(base_url="http://" + ip + ":18080/api")
    #1、若为获取微信与手机号码
    #2、判断是否有私信按钮
    #3、获取私信按钮位置
    #4、点击私信按钮
    #5、输入微信号
    #6、发送
    #7、返回


    # now = datetime.now()
    # formatted_date = now.strftime("%Y_%m_%d")
    # filepath = os.path.join(formatted_date, "AIGC","1751626066853.jpg")

    # response = http_client.get("screenShotBase64")
    # path_or_base64 = response['data']

    image_data = base64.b64decode(
        path_or_base64.split(',')[1] if path_or_base64.startswith('data:image') else path_or_base64)


    with io.BytesIO(image_data) as buffer, Image.open(buffer) as image:
        # 进行裁剪，获取需要的区域
        temp_image = image.crop((0, 712, 1080, 1500))

        text = imgPrivateOcr(temp_image,ocr_engine)
        coordinates = []


        for item in text:
            if item[1] == "私信":
                coordinates = item[0]

        all_text = ''
        for item in text:
            all_text = all_text +" "+ item[1]

        keywords = extract_keywords(all_text)
        if len(keywords)>0:
            return  False

        print(coordinates[0][1])

        data = {"x": 744.0, "y": 712.0+coordinates[0][1]}
        response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("打开私信成功")

        time.sleep(3)

        data = {"x": 300.0, "y": 2190.0}
        response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("点击输入框")

        keyword = random.choice(private_message_List)
        time.sleep(3)
        data = {"value": keyword}
        response = http_client.post("inputText", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("设置私信内容")

        time.sleep(2)
        #返回按钮
        data = {"value": 4}
        response = http_client.post("pressKeyCode", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("隐藏键盘")

        time.sleep(2)
        # 返回按钮
        data = {"x": 995.0, "y": 2195.0}
        response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("发送")

        time.sleep(3)
        #返回按钮
        data = {"value": 4}
        response = http_client.post("pressKeyCode", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("返回")

        return True
# privateMessage("10.88.80.91")



